<script lang="ts" setup>
import { queryDepositDeduction, revokeDepositDeduction } from '@/api/expense'
import { queryDepositDeductionTableCol } from '@/api/expense/types/expense'
import { useActivated } from '@/hooks/useActivated'
import { useTable } from '@/hooks/useTable'
import { getToken } from '@/utils/cache/cookies'
import { onActivated, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import { Action, ElMessage, ElMessageBox } from 'element-plus'
const route = useRoute()
defineOptions({
  name: 'DepositDeductionRecord'
})
const form = reactive({
  orderId: route.query.orderId as string
})
const { pagination, data, loading, handleSizeChange, handleCurrentChange, load } =
  useTable<queryDepositDeductionTableCol>(queryDepositDeduction, getToken() ?? '', () => form)

onActivated(() => {
  form.orderId = (route.query.orderId as string) || ''
})
/** 处理是否缓存 */
useActivated(
  form,
  { form },
  [
    { key: 'orderId', path: 'form.orderId' },
    { key: 'operationType', path: 'form.operationType' }
  ],
  load,
  []
)
onMounted(() => {
  load()
})

const handleRevoke = async (row: queryDepositDeductionTableCol) => {
  const res = await revokeDepositDeduction({
    orderLoggingId: row.orderLoggingId,
    token: getToken() ?? ''
  })
  if (res.statusCode === '0') {
    ElMessage.success(res.data)
    load()
  }
}

const open = (row: queryDepositDeductionTableCol) => {
  ElMessageBox.alert('撤销抵扣后,需要前往重新添加,是否需要撤回该条押金抵扣', '提示', {
    // if you want to disable its autofocus
    // autofocus: false,
    showCancelButton: true,
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    callback: (action: Action) => {
      if (action === 'confirm') {
        handleRevoke(row)
      }
    }
  })
}
</script>

<template>
  <div class="xy-container">
    <el-table :data="data" v-loading="loading">
      <el-table-column prop="type" label="抵扣类型" />
      <el-table-column prop="reason" label="抵扣原因" />
      <el-table-column prop="amount" label="抵扣金额" />
      <el-table-column prop="remainDeposit" label="剩余押金" />
      <el-table-column prop="createdTime" label="抵扣时间" />
      <el-table-column label="操作">
        <template #default="scope">
          <el-button type="primary" class="is-open" link @click="open(scope.row)">撤回</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div flex justify-end mt-20>
      <el-pagination
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        background
        :total="pagination.total"
        layout="total,prev,pager,next,jumper,sizes"
      />
    </div>
  </div>
</template>

<style scoped></style>
